# coding=utf-8

import asyncio
import threading
import time
from manager import pushNotifications
from flask import request, jsonify
from flask_restful import Resource
# from manager.models import db, GateTrade
from manager import gateDao
from gate.gatews import GateWS
from debug import test04
from manager.models import GatePair,GatePairSchema

from gate import gateWebsocket

pairs_schema = GatePairSchema(many=True)
pair_schema = GatePairSchema()

class GlobalResource(Resource):
    def get(self, fun):
        # pushNotifications.all()

        print('\n \n')
        print('----------------------------------------------------------------------------')
        print('- 已 激 活 的 线 程数为：     %d' % threading.active_count())
        print('- 查看现在正在运行的线程：     %s' % threading.current_thread())
        print('- 当 前 运 行 线 程数为：     %s' % threading.enumerate())
        print('- %d --- %s' % (len(gateWebsocket.all_Thread),gateWebsocket.all_Thread))
        print('- %s' % [ws.pair_name for ws in gateWebsocket.all_Thread])
        # print('- %s' % [ws.pair_name for ws in GateWS.all_ws])
        print('----------------------------------------------------------------------------')
        print('\n \n')

        if int(fun) == 1:
            test04.test_ws_quote(1001, 'EOS_USDT')
            return {"message": "test04.test_ws_quote(1001, 'EOS_USDT')"}

        elif int(fun) == 2:
            test04.run_ws()
            return {"message": "test04.run_ws()"}

        elif int(fun) == 3:
            pair_list = gateDao.query_pairs(autosync=1)
            # for pair in pair_list:
            #     gateWebsocket.create_ws(pair.pair_name)
            #     time.sleep(2)

            for i in range(len(pair_list)):
                test04.run_ws(1001+i*3, pair_list[i].pair_name)
            return {"message": "gateDao.query_pairs(1)", "data":pair_list}


        return {"message": "Hello !!!!!!"}

    def put(self):

        ws = gateWebsocket.all_Thread[0]
        gateWebsocket.all_Thread.pop(0)
        ws.close()
        return {"message":('关闭 --- ' + ws.pair_name)}


    def post(self):

        json_data = request.get_json(force=True)

        if 'pair_name' in json_data:

            gateWebsocket.create_ws(json_data['pair_name'])

            # gatews = gateWebsocket.create_ws(json_data['pair_name'])
            # gateWebsocket.all_Thread.append(gatews)
            # gateWebsocket.on_start(gatews)

            # ws = GateWS(json_data['pair_name'])
            # ws.start_ws()

            return {"status": 'success', 'message': '正在开启监控'}, 201


        return {"status": 'fail', 'message': '参数错误'}, 400

